package ru.javadevelop.vegetarian.background;

import android.content.Context;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.DefaultedHttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import ru.javadevelop.vegetarian.R;
import ru.javadevelop.vegetarian.common.ExtApplication;
import ru.javadevelop.vegetarian.common.StringUtils;
import ru.javadevelop.vegetarian.model.Category;
import ru.javadevelop.vegetarian.model.Favorite;
import ru.javadevelop.vegetarian.model.Image;
import ru.javadevelop.vegetarian.model.Recipe;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class JsonGetter {
    Context _context;
    private static final String TAG = "JsonGetter";

    public JsonGetter(Context context)
    {
        this._context = context;
    }

    //******************************************************************************************************************
    //  /api/recipes/AllRecipes/1361972314000
    public ArrayList<Recipe> getRecipesFromDate(Date date)
    {
        ArrayList<Recipe> recipes = null;
        String _getResponse = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(_context.getString(R.string.serviceAddress) + "recipes/AllRecipes/"+date.getTime());
        HttpResponse response;

        try {
            response = httpclient.execute(httpget);

            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();
                String result = StringUtils.convertStreamToString(instream);
                JSONArray json = new JSONArray(result);
                recipes = new ArrayList<Recipe>();
                for (int idx = 0; idx < json.length(); idx++) {
                    JSONObject item = json.getJSONObject(idx);
                    Recipe recipe = new Recipe(
                            item.getInt("Id"),
                            item.getString("AddedByUser"),
                            item.getInt("CategoryId"),
                            StringUtils.parseDate8601(item.getString("Date")) ,
                            item.getString("Ingredients"),
                            item.getString("Name"),
                            item.getString("Process"),
                            item.getInt("Raiting")
                    );
                    recipes.add(recipe);
                }
                instream.close();
            }

        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        }
        int size=0;
        if (recipes!=null)
        {
            size = recipes.size();
        }
        Log.i(TAG, String.valueOf(size)+" recipes syncronised");
        return recipes;
    }
    //******************************************************************************************************************
    // /api/recipes/FindRecipe/3
    public Recipe getRecipeById(int id) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(_context.getString(R.string.serviceAddress) + "recipes/FindRecipe/"+String.valueOf(id));
        HttpResponse response;

        try {
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                String result = StringUtils.convertStreamToString(instream);
                JSONObject json = new JSONObject(result);
                Recipe recipe = new Recipe(
                    json.getInt("Id"),
                    json.getString("AddedByUser"),
                    json.getInt("CategoryId"),
                    StringUtils.parseDate8601(json.getString("Date")) ,
                    json.getString("Ingredients"),
                    json.getString("Name"),
                    json.getString("Process"),
                    json.getInt("Raiting")
                );
                instream.close();
                Log.i(TAG, "Syncronised recipe by id = "+recipe.id);
                return recipe;
            }

        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        }
        throw new Exception("Can't get recipe from web-service.");
    }
    //******************************************************************************************************************
    // /api/categories/getcategories
    public ArrayList<Category> getCategories()
    {
        ArrayList<Category> categories = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(_context.getString(R.string.serviceAddress) + "categories/getcategories/");
        HttpResponse response;

        try {
            response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                String result = StringUtils.convertStreamToString(instream);
                JSONArray json = new JSONArray(result);
                categories = new ArrayList<Category>();
                for (int idx = 0; idx < json.length(); idx++) {
                    JSONObject item = json.getJSONObject(idx);
                    Category category = new Category(
                            item.getInt("Id"),
                            item.getInt("ParentId"),
                            item.getString("Name")
                    );

                    categories.add(category);
                }
                instream.close();
            }
        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        }
        int size=0;
        if (categories!=null)
        {
            size = categories.size();
        }

        Log.i(TAG, String.valueOf(size)+" categories recived.");
        return categories;
    }
    //******************************************************************************************************************
    public ArrayList<Image>  getImagesForRecipe(int recipeId)
    {
        ArrayList<Image> images = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(_context.getString(R.string.serviceAddress) + "images/GetImagesByRecipe/"+recipeId);
        HttpResponse response;

        try {
            response = httpclient.execute(httpget);

            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();
                String result = StringUtils.convertStreamToString(instream);
                JSONArray json = new JSONArray(result);
                images = new ArrayList<Image>();
                for (int idx = 0; idx < json.length(); idx++) {
                    JSONObject item = json.getJSONObject(idx);
                    Image image = new Image(
                            item.getInt("Id"),
                            item.getString("Name"),
                            StringUtils.parseDate8601(item.getString("Date")),
                            item.getInt("RecipeId")
                    );

                    images.add(image);
                }
                instream.close();
            }

        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        }
        Log.i(TAG, "Images for recipe recived. RecipeId="+recipeId);
        return images;
    }
    //******************************************************************************************************************
    public ArrayList<Favorite>  getFavoritesForUser(String username)
    {
        ArrayList<Favorite> favorites = null;
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(_context.getString(R.string.serviceAddress) + "favorites/getFavorites?param="+username);
        HttpResponse response;

        try {
            response = httpclient.execute(httpget);

            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();
                String result = StringUtils.convertStreamToString(instream);
                JSONArray json = new JSONArray(result);
                favorites = new ArrayList<Favorite>();
                for (int idx = 0; idx < json.length(); idx++) {
                    JSONObject item = json.getJSONObject(idx);
                    Favorite favorite = new Favorite(
                            item.getString("Username"),
                            item.getInt("RecipeId"),
                            false
                    );

                    favorites.add(favorite);
                }
                instream.close();
            }

        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        }
        Log.i(TAG, "Recived favorites for user "+username);
        return favorites;
    }
    //******************************************************************************************************************
    public boolean   putFavoriteToServer(String username, int recipe_id)
    {
        boolean result= false;
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost( _context.getString(R.string.serviceAddress) + "favorites/PostFavorite/");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("recipeId", String.valueOf(recipe_id)));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        HttpResponse response;

        try {
                response = httpclient.execute(httpPost);
                if (response.getStatusLine().getStatusCode()==500)
                {
                    Log.i(TAG, "Fav was NOT sended to server. RecipeId=" + recipe_id);
                    result = false;
                }
                else
                {
                    Log.i(TAG, "Fav is sended to server. RecipeId=" + recipe_id);
                    result = true;
                }

        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        }
        return result;
    }
    //******************************************************************************************************************
    /**
     * Вызывает на сервере метод удаления старых избранных блюд
     * @param username
     */
    public void deleteOldFavForUser(String username)
    {
        // TODO: запилить реализацию на серверной части
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(_context.getString(R.string.serviceAddress) + "favorites/DeleteOld/"+username);
        HttpResponse response;

        try {
            response = httpclient.execute(httpget);
        }
        catch (Exception e)
        {
            throw  new RuntimeException(e);
        }
    }
    //******************************************************************************************************************
    //******************************************************************************************************************
    //******************************************************************************************************************
}
